package test;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.Student;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import util.JSONUtil;

@WebServlet("/ajax")
public class AjaxServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("AjaxServlet.doGet()");
		// 不管前台是form表单，还是ajax传递过来的数据，都是通过req.getParameter拿到数据
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		System.out.println("name: " + name);
		System.out.println("age: " + age);

		// 解决服务器返回浏览器乱码问题
		// resp.setContentType("text/html;charset=utf-8");
		// {"name":"王五","age":24}
		// resp.getWriter().write("{\"name\":\"王五\",\"age\":24}");
		
		 Student student = new Student(1, "张三44", 23, "男");
		// List<Student> list;
		
//		JsonConfig jsonConfig = new JsonConfig();
//		String json = JSONObject.fromObject(student, jsonConfig).toString();
//		
//		resp.setContentType("text/json;charset=utf-8");
//		try {
//			resp.getWriter().println(json);
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		 
		 try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		 
		 JSONUtil.obj2Json(student, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("AjaxServlet.doPost()");
		 this.doGet(req, resp);

		// 不管前台是form表单，还是ajax传递过来的数据，都是通过req.getParameter拿到数据
//		String name = req.getParameter("name");
//		String age = req.getParameter("age");
//		System.out.println("name: " + name);
//		System.out.println("age: " + age);
//
//		// 解决服务器返回浏览器乱码问题
//		resp.setContentType("text/html;charset=utf-8");
//		// {"name":"王五","age":24}
//		resp.getWriter().write("{\"name\":\"王五1\",\"age\":25}");
	}
}
